/*
 * @Author: xuhy
 * @Date: 2022-04-03 16:19:21
 * @LastEditTime: 2022-04-04 15:45:30
 * @LastEditors: Please set LastEditors
 * @Description: 配置路由相关规则
 * @FilePath: \vue_shop\src\router\index.js
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginUser from '../components/LoginUser'
import HomeAccess from '../components/HomeAccess'
import WelcomePage from '../components/WelcomePage'
import UsersList from '../components/user/UsersList'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: LoginUser },
    {
      path: '/home',
      component: HomeAccess,
      // 路由重定向
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: WelcomePage },
        { path: 'users', component: UsersList }
      ]
    }
  ]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from从哪个路径跳转
  // next是一个函数，表示放行
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})
export default router
